//
//  HMComposeViewController.swift
//  WymanWeibo
//
//  Created by wyman on 16/4/19.
//  Copyright © 2016年 wyman. All rights reserved.
//

import UIKit

import SVProgressHUD

class HMComposeViewController: UIViewController {

    private var maxOflenth = 25
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        
        prepareUI()
        
        //监听键盘frame的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didChangeFrame:"), name: UIKeyboardWillChangeFrameNotification, object: nil)

        
       
        
    }
    
    //键盘改变的监听方法
    @objc private func didChangeFrame(notification: NSNotification){
    
    //拿到fame值,让textview跟着改变
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue


        let y = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
    
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(y)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    
    }

    deinit{
    
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    func prepareUI(){
    
    setupNavigationBar()
    
    //添加工具条
        /*
        1.UIScrollView或子类
        2.在导航控制器,tabBarControl里面
        3.UIScrollView或子类必须是控制器的view,或者UIScrollView或子类是控制器的view第一个子view,或者UIScrollView或子类是控制器的view第一个子view的第一个子view
        */

        setupTextView()
        setupToolBar()
        
        setupLenthTipLabel()
    
    
    }
    
    private func setupLenthTipLabel(){
    
        view.addSubview(lenthTipLabel)
        
        lenthTipLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolBar.snp_top).offset(-4)
            make.trailing.equalTo(toolBar).offset(-4)
        }
    
    
    }
    
    private func setupTextView(){
    
        view .addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    
    
    }
  
    
    func setupToolBar(){
    
        view.addSubview(toolBar)
        
        //设置工具条
        //添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
    
  //添加五个东西,每个item对应的图片名字
        let itemSetting = [
            
        ["imageName": "compose_mentionbutton_background","action": "mention:"],
            
        ["imageName": "compose_emoticonbutton_background","action": "emoticon:"],
            
        ["imageName": "compose_trendbutton_background","action": "trend:"],
        
        ["imageName": "compose_toolbar_picture","action": "picture:"],
        
        ["imageName": "compose_add_background","action": "add:"],

        ]
    
        var items = [UIBarButtonItem]()
        var index = 0
        
        //遍历数组
        for dict in itemSetting{
        
        let imageName = dict["imageName"]!
         
        //设置加载图片
        let action  = dict["action"]!
            
        let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action))
            
        items.append(item)
        
        let button = item.customView as! UIButton
            
        button.tag = index
            
        items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        
        index++
        }
        
        items.removeLast()
        
        toolBar.items = items
    }
    
    //实现点击方法
    @objc private func mention(){
    
        textView.inputView = textView.inputView == nil ? emoticonKeyboard :nil

    
    }
    
    //切换键盘表情
    @objc private func emoticon(button: UIButton){
        
                //设置toolBar的按钮
        var normalImage: UIImage?
        var highlightedImage: UIImage?
        
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView == nil ? emoticonKeyboard :nil

        if textView.inputView == nil {
            
        normalImage = UIImage(named: "compose_emoticonbutton_background")
        highlightedImage = UIImage(named: "compose_emoticonbutton_background_highlighted")
            
        
        }else{
            normalImage = UIImage(named: "compose_keyboardbutton_background")
            highlightedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")

        }
        
       button.setImage(normalImage, forState: .Normal)
        button.setImage(highlightedImage, forState: .Highlighted)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
        
        
        
    }
    @objc private func trend(){
        
        
        
    }
    
    @objc private func picture(){
        
        
        
    }
    
    @objc private func add(){
        
        
        
    }
    private func setupNavigationBar(){
        
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: Selector("close"))
        
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发微博", style: .Plain, target: self, action: Selector("sendStatus"))
    
    navigationItem.rightBarButtonItem?.enabled = false
        
    setupTitleView()
    
    }
    //设置标题
    private func setupTitleView(){
    
    let prefix = "发微博"
    //先拿到微博名字,有可能拿不到名字
    if let name = HMUserAccountViewModel.shareInstance.userAccount?.screen_name {
        
        let title = prefix + "\n" + name
    let titleView =  UILabel(fontSize: 14, textColor: UIColor.blackColor())
    titleView.text = title
    titleView.numberOfLines = 0
    titleView.textAlignment = .Center
    
        //使用属性文本
        let attStringM = NSMutableAttributedString(string: title)
        
        let range = (title as NSString).rangeOfString(name)
        
        attStringM.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: range)
        
        attStringM.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        
        titleView.attributedText = attStringM
        
        titleView.sizeToFit()
        navigationItem.titleView = titleView

    }else{
        
        navigationItem.title = prefix
        
        
        }
        
        
    
    
    }
    
    
    //点击按钮方法
    @objc private func sendStatus(){
    
    //发送微博
        let text = textView.emoticonText()
        
        let last = maxOflenth - text.characters.count
        if last < 0 {
        
            SVProgressHUD.showErrorWithStatus("超出最大长度")
            return
        }
        
        //提示正在发微博
        SVProgressHUD.showWithStatus("正在发送微博")
        
        HMStatusViewModel.sharedInstance.sendSttus(text) { (error) -> () in
            if error != nil{
            SVProgressHUD.showErrorWithStatus("发送失败")
            return
                
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(),
                { () -> Void in
                    // 发布微博成功了, 关闭控制器
                    self.close()
            })
        }
        
    
    }
    
    @objc private func close(){
    
        textView.resignFirstResponder()
       dismissViewControllerAnimated(true, completion: nil)

    
    }
    
    //懒加载
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var textView: HMPlaceHoldTextView = {
    let tv = HMPlaceHoldTextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.blackColor()
        
        tv.placeholder = "我是占位文本"
        tv.delegate = self
        
        
        tv.alwaysBounceVertical = true
        
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return tv
    
    }()
    
    //懒加载表情

    private lazy var emoticonKeyboard: HMEmoticonKeyboard = {
        let keyboard = HMEmoticonKeyboard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    //长度提示label
    private lazy var lenthTipLabel: UILabel = {
        
        let label = UILabel(fontSize: 10, textColor: UIColor.darkGrayColor())
        
        label.text = String(self.maxOflenth)
        label.sizeToFit()
        
        return label
    }()
    
}

extension HMComposeViewController: UITextViewDelegate{

  
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        let text = textView.emoticonText()
        
        let last = maxOflenth - text.characters.count
        
        lenthTipLabel.text = String(last)
        
        let color = last < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        
        lenthTipLabel.textColor = color
    }



}






